package com.hulk.boot.web.exceptionhandler;

import javax.servlet.http.HttpServletRequest;

import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.base.Throwables;
import com.hulk.boot.common.exception.BaseException;
import com.hulk.boot.common.exception.BaseRteException;

import lombok.extern.slf4j.Slf4j;

/**
 * @author cmt
 *
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = BaseException.class)
    @ResponseBody
    public HttpErrorInfo<String> jsonErrorHandler(HttpServletRequest req, BaseException e) throws Exception {
        HttpErrorInfo<String> r = new HttpErrorInfo<>();
        r.setMessage(e.getErrorMessage());
        r.setCode(e.getErrorCode());
        r.setData("Some Data:"+e.getClass().getSimpleName());
        r.setUrl(req.getRequestURL().toString());
        return r;
    }
    
    
    @ExceptionHandler(value = BaseRteException.class)
    @ResponseBody
    public HttpErrorInfo<String> jsonErrorHandler(HttpServletRequest req, BaseRteException e) throws Exception {
        HttpErrorInfo<String> r = new HttpErrorInfo<>();
        r.setMessage(e.getErrorMessage());
        r.setCode(e.getErrorCode());
        r.setData("Some Data:"+e.getClass().getSimpleName());
        r.setUrl(req.getRequestURL().toString());
        return r;
    }
    
    
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public HttpErrorInfo<String> jsonErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        HttpErrorInfo<String> r = new HttpErrorInfo<>();
        r.setMessage(Throwables.getStackTraceAsString(e));
        r.setCode(String.valueOf(HttpErrorInfo.ERROR));
        r.setData("Some Data:"+e.getClass().getSimpleName());
        r.setUrl(req.getRequestURL().toString());
        return r;
    }
    
    @ModelAttribute
	public void addAttribute(Model m) {
		m.addAttribute("msg", "bye");
		log.debug("============应用到所有@RequestMapping注解方法，在其执行之前把返回值放入Model");
	}

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		log.debug("============应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器");
	}

}